const express = require("express");
const SQLConnect = require("./SQLConnect");
const router = express.Router();
const jwt = require("jsonwebtoken")
const config = require("./config")
const url = require("url");
const multer = require("multer")
const fs = require("fs");

/* 登入接口 */
router.post("/login",(req,res)=>{
  const username = req.body.username
  const password = req.body.password
  const sql = "select * from user where username=? and password=?"
  var arr = [username,password]
  SQLConnect(sql,arr,result=>{
    if(result.length > 0){
      const token = jwt.sign({
        username:username,
        password:password
      },config.jwtSecret)
      res.send({
        status: 200,
        data: result,
        token:token
      })
    }else{
      res.send({
        status: 500,
        msg: "用户名密码错误"
      })
    }
  })
});
// 注册接口
router.post("/register",(req,res)=>{
  const username = req.body.username;
  const password = req.body.password;
  const sql = "insert into user values (null,?,?,null)"
  const arr = [username,password]
  SQLConnect(sql,arr,result=>{
    if(result.affectedRows > 0){
      res.send({
        status: 200,
        msg: "注册成功"
      })
    }else{
      res.send({
        status: 500,
        msg: "注册失败"
      })
    }
  })
})
/* 查询商品接口，请求方式：get，参数：page */
router.get("/book",(req,res)=>{
  // console.log('第三个参数为true：',url.parse('//z.http.cn/information/product?page=1',true,true))
  const page = url.parse(req.url,true).query.page || 1;
  const sql = "select * from project order by id desc limit 10 offset " + (page - 1) * 10;
  SQLConnect(sql,null,result => {
    if(result.length > 0){
      res.send({
        status: 200,
        data: {
          result
        }
      })
    }else {
      res.send({
        status: 500,
        msg: "暂无数据"
      })
    }
  })
})
// 查询总条数
router.get("/total",(req,res)=>{
  const sql = "select count(*) from project where id";
  SQLConnect(sql,null,result=>{
    if(result.length > 0){
      res.send({
        status: 200,
        result
      })
    }else{
      res.send({
        status: 500,
        msg: "查询失败"
      })
    }
  })
})
// 删除商品
router.get("/deleteBook",(req,res) => {
  const id = url.parse(req.url,true).query.id;
  const sql = "delete from project where id=?";
  const arr = [id];
  SQLConnect(sql,arr,result=>{
    
    // 删除返回的是影响行数
    if(result.affectedRows > 0){
      res.send({
        status: 200,
        success: true
      })
    }else{
      res.send({
        status: 500,
        msg: "删除失败"
      })
    }
  })
})
// 类目选择接口
router.get("/selectItemCategoryByParentId",(req, res) => {
  const id = url.parse(req.url,true).query.id || 1;
  const sql = "select * from category where id=?";
  var arr = [id]
  SQLConnect(sql,arr,result => {
    if(result.length > 0){
      res.send({
        status: 200,
        data: result
      })
    }else{
      res.send({
        status: 500,
        msg: "暂无数据"
      })
    }
  })
})
/* 上传图片
   第三方依赖：multer，对文件上传下载
*/
// 指定上传的路径和文件名称
var storage = multer.diskStorage({
  destination:function(req,file,callback){
    callback(null,"./mock/upload/")
  },
  filename:function(req,file,callback){
    callback(null,Date.now() + "-" + file.originalname)
  }
})
// fs(文件系统)
var createFolder = function(folder) {
  try{
    fs.accessSync(folder);
  } catch(e){
    fs.mkdirSync(folder)
  }
}

var uploadFolder = "./mock/upload/";
createFolder(uploadFolder)
var upload = multer({ storage: storage})

router.post('/upload', upload.single('file'), function(req,res,next){
  var file = req.file;
  res.json({res_code: '0', name: file.originalname, url: file.path });
})

// 添加商品
router.get("/insertTbItem",(req,res)=>{
  var title = url.parse(req.url,true).query.title || "";
  var cid = url.parse(req.url,true).query.cid || "";
  var sellPoint = url.parse(req.url,true).query.sellPoint || "";
  var price = url.parse(req.url,true).query.price || "";
  var num = url.parse(req.url,true).query.num || "";
  var desc = url.parse(req.url,true).query.desc || "";
  var image = url.parse(req.url,true).query.image || "";

  const sql = "insert into project values (null,?,?,?,?,?,?,'',1,'','',?)"
  var arr = [title,image,sellPoint,price,cid,num,desc];
  SQLConnect(sql,arr,result =>{
    if(result.affectedRows > 0){
      res.send({
        status: 200,
        success:true,
      })
    }else{
      res.send({
        status:500,
        msg:"添加失败"
      })
    }
  })
})
// 预更新接口 - 编辑
router.get("/preUpdateItem",(req,res)=>{
  const id = url.parse(req.url,true).query.id;
  const sql = "select * from project where id=?"
  const arr = [id];
  SQLConnect(sql,arr,result => {
    if(result.length > 0){
      res.send({
        status: 200,
        data:result[0],
      })
    }else{
      res.send({
        status: 200,
        msg: "暂无数据"
      })
    }
  })
})
// 更新数据接口
router.get("/updateTbItem",(req,res)=>{
  var id = url.parse(req.url,true).query.id;
  var title = url.parse(req.url,true).query.title || "";
  var sellPoint = url.parse(req.url,true).query.sellPoint || "";
  var price = url.parse(req.url,true).query.price || "";
  var num = url.parse(req.url,true).query.num || "";

  var sql = "update project set title=?,sellPoint=?,price=?,num=? where id=?";
  var arr = [title,sellPoint,price,num,id];
  SQLConnect(sql,arr,result=>{
    console.log('affectedRows',result);
    if(result.affectedRows > 0){
      res.send({
        status: 200,
        success: true
      })
    }else{
      res.send({
        status:500,
        msg: "修改失败"
      })
    }
  })
})
/* 规格参数查询，请求方式：get，参数：page */
router.get("/selectItemParamAll",(req,res)=>{
  const page = url.parse(req.url,true).query.page || 1;
  const sql = "select * from params order by id desc limit 10 offset " + (page - 1) * 10;
  SQLConnect(sql,null,result => {
    if(result.length > 0){
      res.send({
        status: 200,
        data: {
          result
        }
      })
    }else {
      res.send({
        status: 500,
        msg: "暂无数据"
      })
    }
  })
})
// 规格参数删除接口
router.get("/deleteItemParamById",(req,res)=>{
  const id = url.parse(req.url,true).query.id;
  const sql = "delete from params where id=?";
  const arr = [id];
  SQLConnect(sql,arr,result=>{
    if(result.affectedRows>0){
      res.send({
        status:200,
        success: true
      })
    }else{
      res.send({
        status:500,
        msg:"删除失败"
      })
    }
  })
})
// 添加参数
router.get("/insertItemParam",(req,res)=>{
  const itemCatId = url.parse(req.url,true).query.itemCatId;
  const paramsData = url.parse(req.url,true).query.paramsData;
  //
  const sql = "insert into params values (null,?,?)";
  const arr = [itemCatId,paramsData]
  SQLConnect(sql,arr,result=>{
    if(result.affectedRows>0){
      res.send({
        status:200,
        success: true
      })
    }else{
      res.send({
        status:500,
        msg:"添加失败"
      })
    }
  })
})
// 内容分类管理 导航查询
router.get("/selectContentCategoryByParentId",(req,res)=>{
  const id = url.parse(req.url,true).query.id || 1;
  const sql = "select * from content where id=?";
  const arr = [id];
  SQLConnect(sql,arr,result=>{
    if(result.length > 0){
      res.send({
        status: 200,
        data: result
      })
    }else{
      res.send({
        status:500,
        msg:"暂无数据"
      })
    }
  })
})
// 内容分类管理 导航 增加
router.get("/insertContentCategory",(req,res)=>{
  // 实际上就是数据库的id，因为id来自父节点的pid
  const pid = url.parse(req.url,true).query.pid;
  const name = url.parse(req.url,true).query.name;
  // 实际上就是数据库的pid
  const currentId = Math.floor(Math.random() * 1000000);
  const sql = "insert into content values (?,?,?)";
  const arr = [pid,name,currentId];
  SQLConnect(sql,arr,result=>{
    if(result.affectedRows>0){
      res.send({
        status:200,
        success:true
      })
    }else{
      res.send({
        status:500,
        msg:"添加失败"
      })
    }
  })
})
// 内容分类管理 导航 删除
router.get("/deleteContentCategoryById",(req,res)=>{
  const pid = url.parse(req.url,true).query.pid;
  const sql = "delete from content where pid=?"
  const arr = [pid];
  SQLConnect(sql,arr,result=>{
    if(result.affectedRows>0){
      res.send({
        status:200,
        success:true
      })
    }else{
      res.send({
        status:500,
        msg:"删除失败"
      })
    }
  })
})
// 内容分类管理 导航 编辑
router.get("/updateContentCategory",(req,res)=>{
  const id = url.parse(req.url,true).query.id;
  const name = url.parse(req.url,true).query.name;
  const sql = "update content set name=? where pid=?"
  const arr = [name,id];
  SQLConnect(sql,arr,result=>{
    if(result.affectedRows>0){
      res.send({
        status:200,
        success:true
      })
    }else{
      res.send({
        status:500,
        msg:"修改失败"
      })
    }
  })
})
/* 内容显示，请求方式：get，参数：page */
router.get("/selectContentShow",(req,res)=>{
  const page = url.parse(req.url,true).query.page || 1;
  const sql = "select * from contentinfo order by id desc limit 10 offset " + (page - 1) * 10;
  SQLConnect(sql,null,result => {
    if(result.length > 0){
      res.send({
        status: 200,
        data: {
          result
        }
      })
    }else {
      res.send({
        status: 500,
        msg: "暂无数据"
      })
    }
  })
})
module.exports = router;